/**
 * @file Configuration.cc
 * @brief 配置文件管理类的实现
 */

#include"Configuration.hpp"
#include<fstream>
#include<sstream>
#include"logger.hpp"

// 静态成员初始化
Configuration* Configuration::_Pconfiguration = nullptr;
Configuration::AutoRelease Configuration::_ar;
pthread_once_t Configuration::_once = PTHREAD_ONCE_INIT;

// 获取单例实例（线程安全）
Configuration* Configuration:: getInstance()
{
    pthread_once(&_once,init);
    return _Pconfiguration;
}

// 加载配置文件，路径为./conf/server.conf
bool Configuration::loadFromFile()
    {
        string filename("../conf/server.conf");
        std::ifstream ifs(filename);
        if(!ifs.is_open()){
            MyLogger::getInstance().serverError("Cannot open configuration file: " + filename);
            //文件打开失败
            throw std::runtime_error("Cannot open configuration file: " + filename);
        }
        //一行一行获取配置项
        string line;
        while (std::getline(ifs, line)) {
        // 跳过空行和注释行
        if (line.empty() || line[0] == '#') {
            continue;
        }

        size_t start = line.find_first_not_of(" \t");//找到第一个非空格的下标
        size_t end = line.find_last_not_of(" \t");//找到最后一个非空格下标
        if (start == std::string::npos) continue; // 空行
        //修剪前后空格
        string line1 = line.substr(start,end-start+1);
        //查找有效内容中的空格作为分隔符
        size_t divide = line1.find_first_of(" \t");
        if (divide == std::string::npos) {
            continue; // 忽略无效行
        }
        string key = line1.substr(0,divide);//得到key，头部尾部可能有空格
        string value = line1.substr(divide+1);//得到value，头部尾部可能有空格

        // 去除键和值的空白字符
        size_t key_start = key.find_first_not_of(" \t");
        size_t key_end = key.find_last_not_of(" \t");
        if (key_start == std::string::npos) continue;
        key = key.substr(key_start, key_end - key_start + 1);//得到完整无空格的key

        size_t value_start = value.find_first_not_of(" \t");
        size_t value_end = value.find_last_not_of(" \t");
        if (value_start == std::string::npos) continue;
        value = value.substr(value_start, value_end - value_start + 1);//得到完整无空格的value

        _map[key] = value;
        
        }
        MyLogger::getInstance().serverInfo("reading config file success" );
        return true;

    }
    // 获取配置项的值
    string Configuration::get(const string& key) const {
    auto it = _map.find(key);
    if (it != _map.end()) {
        return it->second;
    }
    MyLogger::getInstance().serverError("Configuration key not found: " + key);
    throw std::runtime_error("Configuration key not found: " + key);
    }

    // 初始化单例实例
    void Configuration:: init(){
        _Pconfiguration = new Configuration();
    }
